/**
 * js tools
 */
var unionTools = {
	ajaxRequest : function(param, url, method, callback) {
		jQuery.ajax({
			type : method,
			url : url,
			data : param,
			dataType : "json",
			success : function(data, textStatus, jqXHR) {
				if (textStatus == 'success') {
					callback(data, 'success');// 成功回调
				} else {
					callback(data, 'failed');
				}
			},
			error : function(XMLHttpRequest, textStatus, errorThrown) {
				callback(null, 'failed');// 失败回调
			}
		});
	},
	isNullValue : function(value) {
		if (value === '' || typeof (value) == 'undefined'||value==='null'||value==null) {
			return false;
		}
		return true;
	},
	formToParams : function(formId) {
		var params = '';
		var o = {};
		var a = jQuery('#' + formId).serializeArray();
		jQuery.each(a, function() {
			params += this.name + '=' + this.value + '&';
		});
		params = params.replace(/&$/, '');
		return params;
	},
	inputValue : function(inputs) {
		var len = inputs.length;
		if (len == 0) {
			return null;
		}
		var params = '';
		for ( var i = 0; i < len; i++) {
			params += inputs[i] + '=' + (jQuery('#' + inputs[i]).val() || '')
					+ '&';
		}
		params = params.replace(/&$/, '');
		return params;
	},
	rootUrl : function() {
		var pathName = window.location.pathname.substring(1);
		var webName = pathName == '' ? '' : pathName.substring(0, pathName
				.indexOf('/'));
		return window.location.protocol + '//' + window.location.host + '/'
				+ webName + '/';
	},
	getCookie : function(name) {
		var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
		if (arr = document.cookie.match(reg))
			return unescape(arr[2]);
		else
			return null;
	},
	setCookie : function(name, value) {
		var Days = 30;
		var exp = new Date();
		exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000);
		document.cookie = name + "=" + escape(value) + ";expires="
				+ exp.toGMTString();
	},
	setErrorMsg : function(message) {
		if (message) {
			jQuery('#errorMsg').css('color', 'red');
			jQuery('#errorMsg').html('');
			jQuery('#errorMsg').html(message);
		}
	},
	setMsgById:function(el,message){
		var $el = jQuery('#'+el);
		if(message&&el){
			$el.css('color', 'red');
			$el.html('');
			$el.html(message);
		}
	},
	setInputValue : function(json) {
		for ( var key in json) {
			$('#' + key).val(json[key]);
		}
	},
	calculateMoney:function(pay,dis,no,el){	
			if(pay>no){
				jQuery("#"+el).html(Math.ceil(pay*(dis*100))/100);
			}else{
				jQuery("#"+el).html(pay);
			}				 
	}
};

function addCookie(name, value, options) {
	if (arguments.length > 1 && name != null) {
		if (options == null) {
			options = {};
		}
		if (value == null) {
			options.expires = -1;
		}
		if (typeof options.expires == "number") {
			var time = options.expires;
			var expires = options.expires = new Date();
			expires.setTime(expires.getTime() + time * 1000);
		}
		document.cookie = encodeURIComponent(String(name)) + "=" + encodeURIComponent(String(value)) + (options.expires ? "; expires=" + options.expires.toUTCString() : "") + (options.path ? "; path=" + options.path : "") + (options.domain ? "; domain=" + options.domain : ""), (options.secure ? "; secure" : "");
	}
}

// 获取Cookie
function getCookie(name) {
	if (name != null) {
		var value = new RegExp("(?:^|; )" + encodeURIComponent(String(name)) + "=([^;]*)").exec(document.cookie);
		return value ? decodeURIComponent(value[1]) : null;
	}
}

// 移除Cookie
function removeCookie(name, options) {
	addCookie(name, null, options);
}

// 货币格式化
function currency(value, showSign, showUnit,priceRoundType) {
	if (value != null) {
		var price;
		if (priceRoundType == "floor") {
			price = (Math.floor(value * Math.pow(10, 2)) / Math.pow(10, 2)).toFixed(2);//向下取整
		} else if (priceRoundType == "ceil") {
			price = (Math.ceil(value * Math.pow(10, 2)) / Math.pow(10, 2)).toFixed(2);//向上取整
		} else {
			price = (Math.round(value * Math.pow(10, 2)) / Math.pow(10, 2)).toFixed(2);//四舍五入
		}
		if (showSign) {
			price = setting.currencySign + price;
		}
		if (showUnit) {
			price += setting.currencyUnit;
		}
		return price;
	}
}

(function($) {
	$.fn.moneyInput = function(options) {
		this.each(function() {
			var reg=new RegExp(",","g");
			var s = this.value.replace(/\s/g,'').replace(reg,''); 
			if(s){
				s = parseFloat((s + "").replace(/[^\d\.-]/g, "")).toFixed(2) + "";//更改这里n数也可确定要保留的小数位  
				var l = s.split(".")[0].split("").reverse(),  
				r = s.split(".")[1];  
				t = "";  
				for(i = 0; i < l.length; i++ )  
				{  
					t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? "," : "");  
				}  
				$(this).val(t.split("").reverse().join("") + "." + r.substring(0,2));
			}
			$(this).bind("cut copy paste", function(e) {  
                e.preventDefault();  
            });  
			
			$(this).bind('blur',function(e){
				var reg=new RegExp(",","g");
				var s = this.value.replace(/\s/g,'').replace(reg,''); 
				if(s){
					s = parseFloat((s + "").replace(/[^\d\.-]/g, "")).toFixed(2) + "";//更改这里n数也可确定要保留的小数位  
					var l = s.split(".")[0].split("").reverse(),  
					r = s.split(".")[1];  
					t = "";  
					for(i = 0; i < l.length; i++ )  
					{  
						t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? "," : "");  
					}  
					$(this).val(t.split("").reverse().join("") + "." + r.substring(0,2));
				}
			});
		});

		return this;
	};
	
	// 令牌
	$(document).ajaxSend(function(event, request, settings) {
		if (!settings.crossDomain && settings.type != null && settings.type.toLowerCase() == "post") {
			var token = getCookie("token");
			if (token != null) {
				request.setRequestHeader("token", token);
			}
		}
	});
	
	$(document).ajaxComplete(function(event, request, settings) {
		var loginStatus = request.getResponseHeader("loginStatus");
		var tokenStatus = request.getResponseHeader("tokenStatus");
		
		if (loginStatus == "accessDenied") {
			$.message("warn", "登录超时，请重新登录");
			window.setTimeout(function() {
				window.location.reload(true);
			}, 2000);
		} else if (tokenStatus == "accessDenied") {
			var token = getCookie("token");
			if (token != null) {
				$.extend(settings, {
					global: false,
					headers: {token: token}
				});
				$.ajax(settings);
			}
		}

	});
})(jQuery);

//令牌
$().ready(function() {
	$("form").submit(function() {
		var $this = $(this);
		if ($this.attr("method") != null && $this.attr("method").toLowerCase() == "post" && $this.find("input[name='token']").size() == 0) {
			var token = getCookie("token");
			if (token != null) {
				$this.append('<input type="hidden" name="token" value="' + token + '" \/>');
			}
		}
	});
});

